package com.btpj.shop.controller;

import cn.hutool.core.util.StrUtil;
import com.btpj.shop.dto.CommonResult;
import com.btpj.shop.dto.UserDto;
import com.btpj.shop.dto.param.UserParam;
import com.btpj.shop.entity.User;
import com.btpj.shop.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

@Api(tags = "用户相关接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImNyZWF0ZWQiOjE1OTk3MjkwODQ0NzYsImV4cCI6MTYwMjMyMTA4NH0.b5nFCD5HL43gL9oe8RU1qQdfO6K3ctRyCE22pEJ4zuIDFcH6i8LmD0d4ZcqGBS9fvRspgWKbn2V4qRc_ukLUSg
     * Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJCVFBKIiwiY3JlYXRlZCI6MTU5OTcwODA1ODgyOSwiZXhwIjoxNjAyMzAwMDU4fQ.diU9gP3O9SRRfG9TrwfknT57xbP78uFx8VPopSIMPyY9eaBjlfYKOxsH0cypx_ZLezOdScC2WeLjcRmg1Fbbag
     */
    @ApiOperation(value = "登录", notes = "输入用户名和密码进行登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "用户名", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "password", value = "密码", paramType = "query", dataType = "String", required = true)
    })
    @PostMapping("/login")
    public CommonResult<String> login(@RequestParam @Validated @NotBlank(message = "用户名不可为空") String name,
                                      @RequestParam @Validated @NotBlank(message = "密码不可为空") String password) {
        if (userService.getUserByName(name) == null) {
            return CommonResult.error("用户不存在");
        }
        String jwtToken = userService.login(name, password);
        if (jwtToken == null) {
            return CommonResult.error("密码错误");
        } else {
            return CommonResult.success(jwtToken, "登录成功");
        }
    }

    @ApiOperation("获取当前登录用户信息")
    @GetMapping("/userInfo")
    public CommonResult<UserDto> getUserInfo() {
        User user = userService.getUserInfo();
        if (user == null) {
            return CommonResult.expired("当前无登录的用户");
        }
        return CommonResult.success(UserDto.entity2Dto(user));
    }

    @ApiOperation("注册用户")
    @GetMapping("/register")
    public CommonResult<Void> register(@RequestParam @Validated @NotBlank(message = "用户名不可为空") String name,
                                       @RequestParam @Validated @NotBlank(message = "密码不可为空") String password) {
        if (userService.getUserByName(name) != null) {
            return CommonResult.error("该用户名已存在");
        }
        if (userService.register(name, password)) {
            return CommonResult.success("注册成功");
        }

        return CommonResult.error("服务器出错，注册失败");
    }

    @ApiOperation(value = "账号退出", notes = "需要前端配合清除header中的Authority(Token)")
    @GetMapping("/logout")
    public CommonResult<Void> logout() {
        return CommonResult.success("用户注销成功");
    }

    @ApiOperation("更新账户密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "password", value = "原密码(为安全,需统一sh256加密)", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "newPassword", value = "新密码(为安全,需统一sh256加密)", paramType = "query", dataType = "String", required = true)
    })
    @PutMapping("/changePwd")
    public CommonResult<Void> changePwd(@RequestParam String password, @RequestParam String newPassword) {
        if (userService.getUserInfo() == null) {
            return CommonResult.error("请先登录要修改密码的账户");
        }

        if (!userService.checkPassword(password)) {
            return CommonResult.error("原密码不正确");
        }

        if (StrUtil.isEmpty(newPassword)) {
            return CommonResult.error("新密码不能设置为空");
        }

        if (userService.changePwd(newPassword)) {
            return CommonResult.success("修改密码成功");
        } else {
            return CommonResult.error("服务器出错，修改密码失败");
        }
    }

    @ApiOperation("更新账户信息")
    @PutMapping("/updateUser")
    public CommonResult<Void> updateUser(@RequestBody UserParam param) {
        if (userService.getUserInfo() == null) {
            return CommonResult.error("请先登录要修改账户信息的账户");
        }

        if (userService.updateUser(param)) {
            return CommonResult.success("更新账户信息成功");
        } else {
            return CommonResult.error("服务器出错，更新账户信息失败");
        }
    }

    @ApiOperation("账户禁用与解除禁用（需要拥有管理员权限）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "要禁用/解除禁用的用户ID", paramType = "query", dataType = "Long", required = true, allowMultiple = true),
            @ApiImplicitParam(name = "locked", value = "是否锁定", paramType = "query", dataType = "Boolean", required = true)
    })
    @PutMapping("/admin/lockOrUnlockUsers")
    public CommonResult<Void> lockOrUnlockUsers(@RequestParam Long[] ids,
                                                @RequestParam @Validated @NotNull Boolean locked) {
        for (Long id : ids) {
            if (!userService.exists(id)) {
                return CommonResult.error("不存在指定ID为" + id + "的用户");
            }
        }

        if (userService.lockOrUnlockUsers(ids, locked)) {
            return CommonResult.success(locked ? "锁定用户成功" : "解锁用户成功");
        } else {
            return CommonResult.error(locked ? "服务器出错，锁定用户失败" : "服务器出错，解锁用户失败");
        }
    }
}
